package com.yueya.media.mongo.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import com.yueya.media.mongo.IGridFsDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Component
public class GridFsDaoImpl implements IGridFsDao {
	private static Logger logger = LoggerFactory.getLogger(GridFsDaoImpl.class);
	@Autowired
	private MongodbFactory mongdbFactory;
	public void setMongdbFactory(MongodbFactory mongdbFactory) {
		this.mongdbFactory = mongdbFactory;
	}
	@Override
	public void save(String id,InputStream in, String fileName, String extendName,Map<String, String> metaData,String bucket) {
		if (null == in) {
			return;
		}
		GridFSInputFile gridFSInputFile = mongdbFactory.getGridFS(bucket).createFile(in, fileName, true);
		if (null != metaData) {
			gridFSInputFile.setMetaData(new BasicDBObject(metaData));
		}
		gridFSInputFile.setId(id);
		gridFSInputFile.setFilename(fileName);
		gridFSInputFile.setContentType(extendName);
		gridFSInputFile.save();
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return;
	}
	@Override
	public GridFSDBFile findById(String Id,String bucket) {
		GridFS gridFs=mongdbFactory.getGridFS(bucket);
		DBObject query = new BasicDBObject("_id",Id);
		GridFSDBFile gridFSFiles = gridFs.findOne(query);
		return gridFSFiles;
	}

	@Override
	public InputStream getInputstream(String Id,String bucket) {
		GridFS gridFs=mongdbFactory.getGridFS(bucket);
		DBObject query = new BasicDBObject("_id",Id);
		GridFSDBFile gridFSFiles = gridFs.findOne(query);
		if(gridFs==null){
			return null;
		}
		return gridFSFiles.getInputStream();
	}
	@Override
	public List<GridFSDBFile> findByMeta(Map<String, String> map,String bucket){
		GridFS gridFs=mongdbFactory.getGridFS(bucket);
		DBObject query = new BasicDBObject();
		query.put("metadata",map);
		List<GridFSDBFile> list=gridFs.find(query);
		return list;
	}

	@Override
	public List<GridFSDBFile> findByMainId(String mainId, String bucket){
		GridFS gridFs=mongdbFactory.getGridFS(bucket);
		DBObject query = new BasicDBObject();
		query.put("metadata.main_id",mainId);
		List<GridFSDBFile> list=gridFs.find(query);
		return list;
	}
	/**
	 * 将查询到的图片文件
	 * 转换为base64 编码的数据
	 * */
/*	public List<String> find(List<GridFSDBFile> files){
		List<String> imgCode=new ArrayList<String>();
		for(int i=0;i<files.size();i++){
			GridFSDBFile gsFile=new GridFSDBFile();
			InputStream in=gsFile.getInputStream();
			ByteArrayOutputStream out=new ByteArrayOutputStream();
	        byte[] buffer=new byte[1024*4];
	        int n=0;
	        try {
				while ( (n=in.read(buffer)) !=-1) {
				    out.write(buffer,0,n);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
	        buffer=out.toByteArray();
	        imgCode.add(MediaHelper.encodeBase64(buffer));
		}
		return imgCode;
	}*/

	@Override
	public void deleteById(String id,String bucket) {
		GridFS gridFs=mongdbFactory.getGridFS(bucket);
		DBObject query = new BasicDBObject("_id",id);
		gridFs.remove(query);
	}

	@Override
	public boolean updateMeta(String id, Map<String, Object> exts,String bucket) {
        GridFS gridFs=mongdbFactory.getGridFS(bucket);
        DBObject query = new BasicDBObject("_id",id);
        GridFSDBFile gridFSFiles = gridFs.findOne(query);
        if(gridFSFiles==null){
        	return false;
		}
        DBObject metaData=gridFSFiles.getMetaData();
        if(metaData==null){
            metaData=new BasicDBObject();
        }
        try {
            metaData.putAll(exts);
            gridFSFiles.setMetaData(metaData);
            gridFSFiles.save();
        } catch (Exception e) {
            logger.error("更新文件信息出错",e);
            return false;
        }
        return true;
	}

	@Override
	public boolean deleteByMeta(Map<String, Object> exts, String bucket) {
		if(exts==null){
			return false;
		}
		GridFS gridFs=mongdbFactory.getGridFS(bucket);
		DBObject query = new BasicDBObject();
		query.put("metadata",exts);
		gridFs.remove(query);
		return true;
	}
    @Override
    public boolean deleteByMainId(String mainId, String bucket) {
        if(StringUtils.isBlank(mainId)){
            return false;
        }
        GridFS gridFs=mongdbFactory.getGridFS(bucket);
        DBObject query = new BasicDBObject();
        query.put("metadata.main_id",mainId);
        gridFs.remove(query);
        return true;
    }

}
